package xyz.scootaloo.oj.offer

import org.junit.Test
import xyz.scootaloo.console.app.support.Tester

/**
 * @author flutterdash@qq.com
 * @since 2021/4/11 23:26
 */
class P50 {

    private fun firstUniqChar(s: String): Char {
        val tableSize = 26
        val cache = IntArray(tableSize)
        val size = s.length
        // 初始值为-1
        for (idx in 0 until tableSize) {
            cache[idx] = -1
        }

        for (idx in 0 until size) {
            val c = s[idx]
            val pos = c - 'a'
            // 此位置的字符已经出现过一次
            if (cache[pos] >= 0) {
                cache[pos] = -2
            }
            // 此位置的字符之前没有出现过
            else {
                // 赋值为下标
                if (cache[pos] == -1)
                    cache[pos] = idx
            }
        }

        var min = Int.MAX_VALUE
        var res = ' '
        for (idx in 0 until tableSize) {
            if (cache[idx] >= 0) {
                if (cache[idx] < min) {
                    min = cache[idx]     // 下标出现位置
                    res = s[min]  // 更新结果
                }
            }
        }

        return res
    }

    @Test
    fun test0() {
        Tester.createTest(this::firstUniqChar)
            .addCase("abaccdeff", 'b')
            .addCase("bb", ' ')
            .addCase("leetcode", 'l')
            .testAndShow()
    }

}
